package fileinfo

import (
	"fms/global"
	"fms/models"
	"fms/tools"
	"fms/tools/app"
	"fms/tools/app/msg"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

/**
 * @author anyang
 * Email: 1300378587@qq.com
 * Created Date:2020-09-20 18:09
 */

func GetFileInfoList(c *gin.Context) {
	var data models.FileInfo
	var err error
	var pageSize = 10
	var pageIndex = 1

	if size := c.Request.FormValue("pageSize"); size != "" {
		pageSize = tools.StrToInt(err, size)
	}
	if index := c.Request.FormValue("pageIndex"); index != "" {
		pageIndex = tools.StrToInt(err, index)
	}

	data.Name = c.Request.FormValue("name")
	data.Tail = c.Request.FormValue("tail")
	data.Remark = c.Request.FormValue("remark")

	data.DataScope = tools.GetUserIdStr(c)
	result, count, err := data.GetPage(pageSize, pageIndex)
	tools.HasError(err, "", -1)

	app.PageOK(c, result, count, pageIndex, pageSize, "")
}

func GetFileInfo(c *gin.Context) {
	var data models.FileInfo
	data.FileId, _ = tools.StringToInt(c.Param("fileId"))
	result, err := data.Get()
	tools.HasError(err, "抱歉未找到相关信息", -1)

	app.OK(c, result, "")
}

func InsertFileInfo(c *gin.Context) {
	var data models.FileInfo
	err := c.ShouldBindJSON(&data)
	data.CreateBy = tools.GetUserIdStr(c)
	tools.HasError(err, "", 500)
	result, err := data.Create()
	tools.HasError(err, "", -1)
	app.OK(c, result, "")
}

func UpdateFileInfo(c *gin.Context) {
	var data models.FileInfo
	err := c.BindWith(&data, binding.JSON)
	tools.HasError(err, "数据解析失败", -1)
	data.UpdateBy = tools.GetUserIdStr(c)
	result, err := data.Update(data.FileId)
	tools.HasError(err, "", -1)

	app.OK(c, result, "")
}

func DeleteFileInfo(c *gin.Context) {
	var data models.FileInfo
	data.UpdateBy = tools.GetUserIdStr(c)

	IDS := tools.IdsStrToIdsIntGroup("fileId", c)
	md5s := tools.MdsStrToIdsIntGroup("md5", c)
	_, err := data.BatchDelete(IDS)
	tools.HasError(err, msg.DeletedFail, 500)
	_, err = data.BatchClean(md5s) // 错误则忽略
	if err != nil {
		global.Logger.Warningf("删除源文件失败:%s", err)
	}
	app.OK(c, nil, msg.DeletedSuccess)
}
